package org.wzl.service.filter;

import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.wzl.service.bo.UserDetail;
import org.wzl.service.exception.BusinessException;
import org.wzl.service.service.CacheService;
import org.wzl.service.service.UserInfoService;
import org.wzl.service.utils.HttpResponseUtil;
import org.wzl.service.utils.JwtUtil;
import org.wzl.service.utils.Resp;

import java.io.IOException;

import static org.wzl.service.constant.RedisKeyConstant.USER_LOGIN_INFO_KEY;
import static org.wzl.service.constant.SecurityConstant.WHITE_URL;

/**
 * @author: 卫志龙
 * @date: 2024年06月28日 23:32
 */
@Slf4j
@Component
public class RequestTokenFilter extends OncePerRequestFilter {

    @Resource
    private CacheService cacheService;

    @Resource
    private UserInfoService userInfoService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");

        String requestURI = request.getRequestURI();

        for (String white : WHITE_URL) {
            if (white.equals(requestURI) || isPathMatch(white, requestURI)) {
                filterChain.doFilter(request, response);
                return;
            }
        }

        if (ObjectUtils.isEmpty(token)) {
            HttpResponseUtil.sendResp(HttpResponseUtil.Response.builder()
                    .httpServletResponse(response)
                    .responseEntity(Resp.fail("token为空"))
                    .build());
            return;
        }

        //解析token，获取用户id
        JwtUtil.UserTokenBO userTokenBO = null;
        try {
            userTokenBO = JwtUtil.parseJwt(token);
        } catch (BusinessException e) {
            HttpResponseUtil.sendResp(HttpResponseUtil.Response.builder()
                    .httpServletResponse(response)
                    .responseEntity(Resp.fail(e.getMessage()))
                    .build());
        }
        //判断jwt是否过期
        if (JwtUtil.isJwtExpired(token)) {
            HttpResponseUtil.sendResp(HttpResponseUtil.Response.builder()
                    .httpServletResponse(response)
                    .responseEntity(Resp.ok("登录信息已过期，请重新登录"))
                    .build());
            return ;
        }

        UserDetail userDetail;

        //根据id从redis获取已登录的用户信息，如果redis为空，从数据库中刷新
        String key = USER_LOGIN_INFO_KEY + userTokenBO.getId();
        userDetail = cacheService.get(key, new TypeReference<>() {
        });
        if (null == userDetail) {
            userDetail = userInfoService.loadUserByUserId(userTokenBO.getId());
        }
        //存入SecurityContextHolder
        var authenticationToken = new UsernamePasswordAuthenticationToken(userDetail,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }

    private static boolean isPathMatch(String pattern, String targetPath) {
        if (pattern.endsWith("/**")) {
            // 如果路径以 "/**" 结尾，则检查前缀是否匹配
            String prefix = pattern.substring(0, pattern.length() - 3);
            return targetPath.startsWith(prefix);
        } else {
            // 否则，直接检查完整路径是否匹配
            return pattern.equals(targetPath);
        }
    }

}
